/* 关于用户的共享数据 */


/* 引入axios */
import axios from "axios"


/* 引入nanoid 用于生成随机字符串 */
import { nanoid } from "nanoid";


/* 暴露整个模块 */
export default {


    /* 开启命名空间 */
    namespaced: true,


    /* 数据 */
    state: {


        /* 用户自定义歌单 */
        mineMusicListObj: JSON.parse(localStorage.getItem('MINEMUSICLIST') || '{}'),


        /* 整个vm 我也不知道获取这个是不是多余了 但是在下面的接口中均用到了 vm身上的某一些东西 */
        vm: null,


        /* 是否第一次进入应用 */
        firstState: true,


        /* 当前播放音乐的索引 */
        m_idx: 0,


        /* 当前播放音乐的播放总时长 */
        musicDuration: 0,


        /* 应用的宽度 */
        screenWidth: 0,


        /* 音乐的数据 */
        musicData: JSON.parse(localStorage.getItem('MUSICDATA') || '[]'),


        /* 全局弹出层 */
        toastObj: {
            toastShow: false,
            toastData: [],
            title: "",
            custom: false
        },


        /* 氛围灯 */
        themes: JSON.parse(localStorage.getItem("THEMES") || JSON.stringify(
            {
                idx: 0,
                colors: [
                    "#ffcff1",
                    "#67c23a",
                    "#E6A23C",
                    "#F56C6C",
                    "#409EFF",
                    "#909399",
                    "#f9d423",
                    "#e65c00"
                ]
            }
        ))
    },

    /* 修改数据的API */
    mutations: {


        /* 获取当前音乐总时长 */
        GETMUSICDURATION(state, value) {
            state.musicDuration = value
        },


        /* 获取vm */
        GETVM(state, vm) {
            state.vm = vm
        },


        /* 视口宽度 */
        CHANGESCREENWIDTH(state, screenWidth) {
            state.screenWidth = screenWidth
        },


        /* 更新仓库里的音乐数据 */
        UPDATEMUSICDATA(state, musicData) {
            state.musicData = musicData
            this.commit("music/_save_music_data")
        },


        /* 更新本地的音乐数据 */
        _save_music_data(state) {
            localStorage.setItem("MUSICDATA", JSON.stringify(state.musicData))
        },


        /* 改变播放音乐索引 */
        CHANGEMUSICIDX(state, m_idx) {
            state.m_idx = m_idx
        },


        /* 根据前台传来的musicId改变音乐的播放状态 */
        PLAY(state, musicId) {
            /* 将所有的状态变成false */
            state.musicData.forEach(e => e.isPlay = false)
            /* 主要逻辑 */
            const find = state.musicData.find(e => e.musicId === musicId)
            find["isPlay"] = true
            this.commit("music/_save_music_data")
        },


        /* 暂停正在播放的音乐 */
        PAUSE(state, musicId) {
            const find = state.musicData.find(e => e.musicId === musicId)
            find["isPlay"] = false
            this.commit("music/_save_music_data")
        },


        /* 弹出层 */
        TOASTOPERA(state, obj) {
            state.toastObj = { ...state.toastObj, ...obj }
        },


        /* 更新第一次进入 */
        CHANGEFIRSTSTATE(state) {
            state.firstState = false
        },


        /* 移除播放列表中的某个音乐 */
        MUSICLISTREMOVE(state, { musicId, idx }) {
            const length = this.getters["music/music_setout"].length
            if (length <= 1) {
                state.vm.$message({
                    showClose: true,
                    message: '必须要留一首歌噢,亲~',
                    type: 'warning',
                    duration: 1000
                });
            } else {
                if (state.m_idx === idx) {
                    state.m_idx = 0
                }
                else if (state.m_idx > idx) {
                    state.m_idx--
                }
                const find = this.getters["music/music_setout"].find(x => x.musicId === musicId)
                if (find) {
                    find["setout"] = false
                    this.commit("music/_save_music_data")
                    state.vm.$message({
                        showClose: true,
                        message: '操作成功！',
                        type: 'success',
                        duration: 1000
                    });
                    return true
                }
                state.vm.$message({
                    showClose: true,
                    message: '操作失败！',
                    type: 'error',
                    duration: 1000
                })
            }


        },


        /* 收藏取消收藏 */
        COLLECT(state, obj) {
            const find = state.musicData.find(x => x.musicId === obj.musicId)
            find["islike"] = !obj["islike"]
            this.commit("music/_save_music_data")
            state.vm.$message({
                message: "操作成功",
                type: "info",
                duration: 1000
            })
        },


        /* 添加到播放列表 */
        ADDSETOUT(state, music) {
            /* 过滤掉这个音乐 */
            const filter = state.musicData.filter(x => x.musicId !== music.musicId)
            state.musicData = filter
            /* 添加这个音乐到播放列表队尾 */
            music["setout"] = true
            state.musicData.push(music)
            this.commit("music/_save_music_data")
            state.vm.$message({
                message: "添加成功",
                type: "success",
                duration: 1000

            })
        },


        /* 添加新的音乐 */
        ADDNEWMUSIC(state, music) {
            // 查询列表里有没有这个音乐
            const find = state.musicData.find(x => x.musicId === music.musicId)
            // 如果有则过滤掉在进行添加,没有就直接添加到队尾
            if (find) {
                state.musicData = state.musicData.filter(x => x.musicId !== find.musicId)
            }
            // state.musicData.splice(0, 0, music)
            state.musicData.push(music)
            const m_idx = this.getters["music/music_setout"].length - 1
            this.commit("music/CHANGEMUSICIDX", m_idx)
            this.commit("music/_save_music_data")
        },


        /* 播放列表里的音乐 */
        PLAYMUSICLIST(state, music) {
            /* 过滤掉这个音乐 */
            const filter = state.musicData.filter(x => x.musicId !== music.musicId)
            state.musicData = filter
            /* 添加这个音乐到播放列表队头 */
            music["setout"] = true
            state.musicData.push(music)
            const m_idx = this.getters["music/music_setout"].length - 1
            this.commit("music/CHANGEMUSICIDX", m_idx)
            this.commit("music/PLAY", music.musicId)
            this.commit("music/_save_music_data")
            state.vm.$message({
                message: "播放成功",
                type: "success",
                duration: 1000

            })
        },


        /* 创建歌单 */
        CREATEMUSICLIST(state, name) {
            /* 添加用户自定义属性 */
            state.vm.$set(state.mineMusicListObj, name, []);
            /* 提交 */
            this.commit("music/_save_mine_music_list")
        },


        /* 将歌单存入本地 */
        _save_mine_music_list(state) {
            localStorage.setItem("MINEMUSICLIST", JSON.stringify(state.mineMusicListObj))
        },


        /* 删除自定义歌单 */
        DELETEMUSICLIST({ vm, mineMusicListObj }, name) {
            vm.$delete(mineMusicListObj, name);
            vm.$notify({
                title: "提示",
                message: "歌单删除成功",
                type: "info",
                position: "top-right",
                duration: 1000,
            });
            this.commit("music/_save_mine_music_list")
        },


        /* 切换氛围灯颜色 */
        SWITCHCOLOR({ vm, themes }, idx) {
            vm.$notify({
                title: '站内消息',
                message: '氛围灯切换成功！',
                offset: 200,
                duration: 500
            })
            vm.$set(themes, "idx", idx)
            this.commit("music/_save_themes")
        },


        /* 添加用户自定义的氛围灯颜色 */
        PUSHUSERCUSTOMTHEME({ vm, themes }, color) {
            vm.$notify({
                title: '站内消息',
                message: '主题添加成功！',
                offset: 200,
                duration: 500
            })
            themes["colors"].push(color)
            this.commit("music/_save_themes")
        },


        /* 保存主题色 */
        _save_themes(state) {
            localStorage.setItem("THEMES", JSON.stringify(state.themes))
        },


        /* 音乐上下架 */
        MUSICUPDOWN(state, { musicId, value }) {
            const find = state.musicData.find(x => x.musicId === musicId)
            state.vm.$set(find, 'state', value)
            this.commit("music/_save_music_data")
        },


        /* 后台添加音乐 */
        BACKADDMUSIC(state, musicObj) {
            state.musicData.push(musicObj)
            this.commit("music/_save_music_data")
        },


        /* 后台删除音乐 */
        BACKDELETEMUSIC(state, musicId) {
            state.musicData = state.musicData.filter(x => x.musicId !== musicId)
            this.commit("music/_save_music_data")
        },


        /* 给当前自定义歌单添加音乐 */
        MUSICLISTPUSHCUR(state, { name, musicData }) {
            state.mineMusicListObj[name].push(musicData)
            this.commit("music/_save_mine_music_list")
        },


        /* 移除当前自定义歌单中的音乐 */
        MUSICLISTREMOVECUR(state, { name, musicData }) {
            state.mineMusicListObj[name] = state.mineMusicListObj[name].filter(x => x['musicId'] !== musicData['musicId'])
            this.commit("music/_save_mine_music_list")
        }
    },


    /* 业务处理 */
    actions: {


        /* 给当前自定义歌单添加/移除音乐 */
        musicListPushRemove({ commit, state }, data) {
            const find = state.mineMusicListObj[data['name']].find(x => x['musicId'] === data['musicData']['musicId'])
            if (find) {
                commit("MUSICLISTREMOVECUR", data)
                state.vm.$message({ message: "移除成功！", type: "info", duration: 500 })
            } else {
                commit("MUSICLISTPUSHCUR", data)
                state.vm.$message({ message: "添加成功！", type: "info", duration: 500 })
            }
        },


        /* 音乐上下架 */
        musicUpDown({ commit, state }, { musicId }) {
            const find = state.musicData.find(x => x.musicId === musicId)
            if (find) {
                const value = find["state"] ? 0 : 1
                const obj = {
                    value,
                    musicId
                }
                if (value) {
                    state.vm.$message({ message: "音乐已下架", type: "success" })
                } else {
                    state.vm.$message({ message: "音乐已上架", type: "success" })
                }
                commit("MUSICUPDOWN", obj)
                return true
            }
            state.vm.$message({ message: "音乐不存在", type: "error" })

        },


        /* 创建歌单业务处理 */
        createMusicList({ commit, state }, name) {
            if (state.mineMusicListObj.hasOwnProperty(name)) {
                state.vm.$alert("创建失败！该歌单名称已经存在！", "提示", { type: "error" });
                return false;
            }
            const loading = state.vm.$loading({
                lock: true,
                text: "歌单创建中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
                target: ".mine-music-list"
            });
            setTimeout(() => {
                state.vm.$nextTick(() => {
                    /* 提交 */
                    commit("CREATEMUSICLIST", name)
                    loading.close();
                    state.vm.$notify({
                        title: "提示",
                        message: "歌单创建成功",
                        type: "success",
                        position: "top-right",
                        duration: 1000,
                    });
                });
            }, 1000);
        },


        /* 检查是否为会员 */
        checkVIP({ commit, state }, value) {
            const getters = this.getters
            if (!getters['user/isLogin']) {
                state.vm.$confirm('请先登录', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    state.vm.$router.push({
                        path: "/login"
                    })
                }).catch(() => {
                    return false
                });
            } else if (!getters['user/isVip']) {
                state.vm.$confirm('该音乐仅会员可播放,是否前往开通', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(() => {
                    state.vm.$router.push({
                        path: "/mine"
                    })
                }).catch(() => {
                    return false
                });
            } else {
                state.vm.$message({
                    message: "播放成功",
                    type: "success",
                    duration: 1000
                })
                commit("ADDNEWMUSIC", value)
            }

        },


        /* 搜索 发送 axios请求*/
        searchRequest({ commit, state }, keyword) {
            state.vm.loading = state.vm.$loading({
                lock: true,
                text: "搜索中...",
                spinner: "el-icon-loading",
                background: "rgba(0, 0, 0, 0.7)",
            });
            axios.get("http://api.btstu.cn/yan/api.php").then(
                (res) => {
                    const obj = [
                        {
                            musicId: nanoid(),
                            name: res.data,
                            src: "https://jsai.312jiah.com/huanting.mp3",
                            author: "佚名",
                            isPlay: false,
                            islike: false,
                            setout: false,
                        },
                    ];
                    state.vm.loading.close();
                    state.vm.$message({
                        message: "搜索成功",
                        type: "success",
                        duration: 1000
                    })
                    commit("TOASTOPERA", {
                        title: `关键字【${keyword}】搜索结果`,
                        toastShow: true,
                        toastData: obj,
                    });
                },
                (err) => {
                    state.vm.$message({ message: err.message, type: "error", duration: 1000 })
                    state.vm.loading.close();
                }
            );
        },


        /* 播放音乐 分3种情况的播放，1.播放列表里点击播放 2.各大歌单列表里的点击播放 3.搜索结果列表的音乐*/
        playMusic(context, data) {
            context.commit("PLAYMUSICLIST", data)
        },
    },


    /* 计算属性 */
    getters: {
        /* 计算回到顶部距离右边的距离 */
        right(state) {
            return state.screenWidth < 768 ? 10 : 40
        },


        /* 计算已收藏的音乐 */
        music_islike(state) {
            return state.musicData.filter(e => e.islike)
        },


        /* 计算播放列表中的音乐 */
        music_setout(state) {
            return state.musicData.filter(e => e.setout)
        },


        /* 计算用户的自定义歌单 */
        mineMusicLists(state) {
            return Object.keys(state.mineMusicListObj);
        },
    }
}